<!--  -->
<template>
  <div class='authority'>
    <el-button type="primary" v-permissions="'role:add'" @click="adduser" style="margin-bottom: 10px;">新增</el-button>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="formInline.value1"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="模糊查询关键字">
        <el-input v-model="formInline.kw" placeholder="请输入关键字"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSrearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table
        :data="tableData"
        style="width: auto">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名"
          width="100">
        </el-table-column>
        <el-table-column
          prop="address"
          width="180"
          label="录入时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="rRemarks"
          width="150"
          label="备注">
        </el-table-column>
        <el-table-column
          label="操作"
          width="150">
          <template slot-scope="scope">
            <el-button v-permissions="'role:detail'" @click="getRoleDetail(scope.row.id,scope.row.roleName,scope.row.rRemarks)" type="text" size="small">详情</el-button>
            <el-button v-permissions="'role:delete'" @click="deletRoleUser(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <!-- 详情 -->
      <el-dialog
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :show-close="false"
        :close-on-press-escape="true"
        width="50%">
        <el-form ref="basicForm" :disabled="isDisable" :inline="false" class="demo-form-inline" label-position="left" label-width="220px">
          <div class="filter-container">
            <el-form-item label="角色名">
              <el-input v-model="userNameGet"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="userRemarkGet"></el-input>
            </el-form-item>
            <el-form-item label="权限">
              <el-tree
                :data="userList"
                show-checkbox
                :check-strictly="defaultRelev"
                :getCheckedNodes="false"
                :default-expand-all="false"
                node-key="id"
                ref="adminTree"
                highlight-current
                :default-checked-keys="defaultCheckRole"
                @check="roleNodeChange"
                :props="defaultProps">
              </el-tree>
            </el-form-item>

          </div>
        </el-form>
        <div class="buttons">
           <el-button type="primary" v-permissions="'role:update'" @click="setConfigUserRole" v-if="isDisable">修改</el-button>
           <el-button type="primary" @click="addConfigUserRole" v-if="!isDisable">保存</el-button>
           <el-button @click="closeDia">关闭</el-button>
        </div>
      </el-dialog>
      <!-- 新增 -->
      <el-dialog
        title="新增角色"
        :visible.sync="addUserShow"
        :close-on-press-escape="true"
        :close-on-click-modal="false"
        width="50%">
        <el-form ref="form" :model="form" :rules="addUserRule" label-width="80px">
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="form.roleName"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark"></el-input>
          </el-form-item>
        </el-form>
        <div style="width: 100%; text-align: center;">
          <el-button type="primary" @click="addRoleUser">保存</el-button>
        </div>
      </el-dialog>
    </div>
    <pagination
      class="pagination_container"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      @pagination="getRouterList"
    />
  </div>
</template>

<script>
import { roleList, roleDtail, roleAdd, roleUpdate, roleDelete } from '@/api/role'
import { parseTime } from '@/until/paramRou'
import Pagination from '@/components/pagination'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    Pagination
  },
  data () {
    return {
      defaultRelev: true,
      isDisable: true,
      formInline: {
        value1: [],
        kw: ''
      },
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      // checked: false,
      dialogVisible: false,
      userNameGet: '',
      userRemarkGet: '',
      userRoleIdGet: null,
      userList: JSON.parse(sessionStorage.getItem('routerList')),
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultCheckRole: [],
      setRoleIdArrFir: [],
      setRoleIdArrSen: [],
      addUserShow: false,
      form: {
        roleName: '',
        remark: ''
      },
      addUserRule: {
        roleName: [
          { required: true, trigger: 'blur', message: '请输入您的姓名' }
        ],
        remark: [
          { required: true, trigger: 'blur', message: '请输入您的备注' }
        ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    submitSrearch () {
      this.getRouterList()
    },
    resetForm () {
      this.formInline.value1 = []
      // this.formInline.value1[0] = null
      // this.formInline.value1[1] = null
      this.formInline.kw = ''
    },
    deletRoleUser (val) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        roleDelete(val).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getRouterList()
          } else {
            this.$message({
              type: 'info',
              message: res
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addRoleUser () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          roleAdd(this.form.remark, this.form.roleName).then(res => {
            if (res.code !== '200') {
              this.$message({
                message: res.message,
                type: 'warning'
              })
            } else {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.addUserShow = false
              this.getRouterList()
            }
            this.form.remark = ''
            this.form.roleName = ''
          })
        }
      })
    },
    getRoleDetail (val, name, rRemarks) {
      this.defaultRelev = true
      console.log(val, name, rRemarks)
      this.userNameGet = name
      this.userRoleIdGet = val
      this.userRemarkGet = rRemarks
      const arrNull = []
      this.defaultCheckRole = []
      roleDtail(val).then(res => {
        if (res.data.length >= 1) {
          for (const key of res.data) {
            arrNull.push(key.id)
            if (key.children) {
              for (const item of key.children) {
                arrNull.push(item.id)
                if (item.children) {
                  for (const jek of item.children) {
                    arrNull.push(jek.id)
                    this.dialogVisible = true
                  }
                } else {
                  this.dialogVisible = true
                  this.defaultCheckRole = []
                }
              }
            } else {
              this.dialogVisible = true
              this.defaultCheckRole = []
            }
          }
        } else {
          this.dialogVisible = true
          this.defaultCheckRole = []
        }
        // this.$refs.adminTree.setCheckedKeys(this.defaultCheckRole)
        this.$nextTick(() => {
          this.defaultCheckRole = arrNull
          this.$refs.adminTree.setCheckedKeys(this.defaultCheckRole)
        })
      })
    },
    setConfigUserRole () {
      this.$confirm('是否确认修改角色信息', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        distinguishCancelAndClose: false
      }).then(() => {
        this.isDisable = false
        this.defaultRelev = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    addConfigUserRole () {
      const newArr = []
      newArr.push(...this.setRoleIdArrFir, ...this.setRoleIdArrSen)
      const role = {
        menuList: newArr.length === 0 ? this.defaultCheckRole : newArr,
        remarks: this.userRemarkGet,
        roleId: this.userRoleIdGet,
        roleName: this.userNameGet
      }
      roleUpdate(role).then(res => {
        this.dialogVisible = false
        if (res.code === '200') {
          this.getRouterList()
          this.isDisable = true
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      })
    },
    closeDia () {
      this.dialogVisible = false
      this.isDisable = true
      this.$nextTick(() => {
        this.defaultCheckRole = []
      })
    },
    adduser () {
      this.addUserShow = true
    },
    getRouterList () {
      if (this.formInline.value1 === null || this.formInline.value1[0] === undefined || this.formInline.value1[1] === undefined) {
        roleList({ limit: this.pagination.pageSize, page: this.pagination.page, kw: this.formInline.kw, startTime: '', endTime: '' }).then(res => {
          if (res.code === '200') {
            this.tableData = res.data.records
            if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
              this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
              this.getRouterList()
            } else {
              this.pagination.total = res.data.total
            }
          } else {
            this.tableData = []
          }
        })
      } else {
        roleList({ limit: this.pagination.pageSize, page: this.pagination.page, kw: this.formInline.kw, startTime: parseTime(this.formInline.value1[0]), endTime: parseTime(this.formInline.value1[1]) }).then(res => {
          if (res.code === '200') {
            this.tableData = res.data.records
            if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
              this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
              this.getRouterList()
            } else {
              this.pagination.total = res.data.total
            }
          } else {
            this.tableData = []
          }
        })
      }
    },
    roleNodeChange (checkedNodes, data) {
      this.setRoleIdArrFir = data.checkedKeys
      this.setRoleIdArrSen = data.halfCheckedKeys
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getRouterList()
  }
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
.authority {
  width: 100%;
  height: 100%;
}
.fir {
  width: auto;
  height: 30px;
  line-height: 30px;
  span {
    margin-left: 10px;
    padding: 5px;
    width: 30%;
  }
}
.sen {
  margin: 5px auto;
  width: 80%;
  padding: 10px;
  border: 1px solid #f0f0f0;
}
.buttons {
  width: 100%;
  text-align: center;
}
</style>
